package com.jarveis.dbs.shfc.common;

import java.util.Date;

import org.apache.log4j.Logger;

import com.jarveis.dbs.core.ConstantFactory;
import com.jarveis.dbs.core.Service;
import com.jarveis.dbs.shfc.common.bean.SmsBean;
import com.jarveis.frame.jdbc.JdbcUtil;
import com.jarveis.frame.lang.DateUtil;
import com.jarveis.frame.util.Param;

public class SendSmsService implements Service {

	private static final Logger logger = Logger.getLogger(SendSmsService.class);

	public Param callService(Param in) {
		Param out = null;

		try {
			out = new Param(Param.RESP);
			String phone = in.getBody().getString("@phone"); // 接收人的手机号码
			String content = ConstantFactory.get("sms_content"); // 短信内容
			Date curDate = DateUtil.getDate(); // 当前时间

			String dindex = DateUtil.getDateStr(curDate,
					DateUtil.FORMAT_YMDHMSS); // 小单号
			String pindex = phone + dindex; // 大单号
			String smsCode = random(6); // 随机号码
			content = content.replace("{1}", smsCode);

			SmsBean smsBean = new SmsBean();
			smsBean.setSmsTo(phone);
			smsBean.setSmsBody(content);
			smsBean.setSmsCode(smsCode);
			smsBean.setPindex(pindex);
			smsBean.setDindex(dindex);
			smsBean.setSmsType("0");
			smsBean.setAccountType("3");// 1:出票通知短信;2:中奖通知短信;3:前台验证短信
			smsBean.setIsSucc("-1");
			smsBean.setIp("");
			// 记录日志信息
			logger.info("pindex=" + pindex + ", dindex=" + dindex);
			if (JdbcUtil.save(smsBean) > 0) {
				out.getHead().setProperty(Param.LABEL_ERROR,
						Param.ERROR_SUCCESS);
			} else {
				out.getHead().setProperty(Param.LABEL_ERROR, 1001);
			}
		} catch (Exception ex) {
			out.getHead().setProperty(Param.LABEL_ERROR, Param.ERROR_EXCEPTION);
			logger.error(ex.getMessage(), ex);
		}

		return out;
	}

	/**
	 * 生成6位随机数（只能包含0-9数字）
	 * 
	 * @return 返回生成后的字符串
	 */
	protected String random(int size) {
		String reStr = "";
		StringBuffer buf = new StringBuffer("");
		String[] arr = new String[] { "0", "1", "2", "3", "4", "5", "6", "7",
				"8", "9" };

		try {
			for (int i = 0; i < size; i++) {
				int rand = (int) (Math.random() * 10);
				buf.append(arr[rand]);
			}
			reStr = buf.toString().toLowerCase();

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		return reStr;
	}

}
